package com.example.clientsideapplication;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Map.Entry;
import java.util.AbstractMap.SimpleEntry;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;

public class InsertOfferService extends IntentService {

	private Socket socket;
	private String serverAddress;
	private int serverSocket;
	private SharedPreferences preferences;
	private ObjectOutputStream outputStream;
	private final static String MY_LOGIN = "myAppLogIn";

	public InsertOfferService() {
		super("InsertOfferService");
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		// TODO Auto-generated method stub
		Offer newOffer = (Offer) intent.getSerializableExtra("offer");

		serverAddress = intent.getStringExtra("serverAddress");
		serverSocket = intent.getIntExtra("serverSocket", 21111);

		try {
			socket = new Socket(serverAddress, serverSocket);
			outputStream = new ObjectOutputStream(socket.getOutputStream());

			preferences = getSharedPreferences(MY_LOGIN, Context.MODE_PRIVATE);
			Integer idMerchant = preferences.getInt("idMerchant", -1);
			Entry<Integer, Offer> entry = new SimpleEntry<Integer, Offer>(
					idMerchant, newOffer);

			DataPackage outputData = new DataPackage(1, entry);
			outputStream.writeObject(outputData);

		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
